<?

class compile_nginx_task extends system_task
{
	public function execute( array $params = array() )
	{
		$this->out('Reading available configurations');
		$config = PROJECT_PATH . '/config/nginx';

		$templates = glob("{$config}/tpl.*");

		foreach ( $templates as $tpl_path )
		{
			$tpl = file_get_contents($tpl_path);
			if ( !$tpl ) return $this->error('Template configuration not found or empty');

			$tpl_ext = str_replace('tpl.', '', basename($tpl_path));
			$files = glob("{$config}/*.{$tpl_ext}");
			foreach ( $files as $file )
			{
				$fname = basename($file);
				if (strpos($fname, 'tpl') === 0 ) continue;

				if ( count(explode('.', $fname)) != count(explode('.', basename($tpl_path))) ) continue;

				$this->out('Generating ' . $fname . '...');

				$params = array();
				$content = file_get_contents($file);
				preg_match_all('/#([a-z_]+)=(.+)/', $content, $m);
				foreach ( $m[1] as $i => $key ) $params[$key] = $m[2][$i];

				$generated = $tpl;
				$src = "# Generated configuration, do not edit\n\n";
				foreach ( $params as $k => $v )
				{
					$src .= "#{$k}={$v}\n";
					$generated = str_replace("{\${$k}}", $v, $generated);
				}

				$src .= "\n\n" . $generated;
				file_put_contents($file, $src);

				$this->out('done!');
			}
		}
	}
}